package com.jessechanrui.template.common.template.auth.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.jessechanrui.template.common.template.auth.application.dto.UserDTO;
import com.jessechanrui.template.common.template.auth.common.AuthorizationSupport;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author chenrui
 * @version 1.0
 * @description UserMetaObjectHandler
 * @date 2025/7/15
 */
public class CustomMetaObjectHandler implements MetaObjectHandler {

    private String tenantId;

    public CustomMetaObjectHandler(String tenantId) {
        this.tenantId = tenantId;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "createUser", String.class, getUserName());
        this.strictInsertFill(metaObject, "updateUser", String.class, getUserName());
        this.strictInsertFill(metaObject, "tenantId", String.class, getTenantId());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateUser", String.class, getUserName());
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }

    private String getUserName(){
        UserDTO currentUser = AuthorizationSupport.getCurrentUser();
        if(currentUser != null){
            return currentUser.getName() + "-" + currentUser.getUserNickname();
        }
        return null;
    }

    private String getTenantId(){
        // TODO： 钩子触发无法获取到租户ID时，暂使用指定的租户； 后续需调整为需通过token，使用哪个租户由主控服务决定
        return AuthorizationSupport.getCurrentTenantId() != null ? AuthorizationSupport.getCurrentTenantId() : tenantId;
    }

}
